package web;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import beans.Member;
import beans.Story;
import service.SaveStoryService;
import serviceimpl.SaveStoryServiceIpmt;

@WebServlet("/FileServlet")
public class FileServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String str = request.getParameter("myStory");
		if(str!=null) {
			Member m = (Member) request.getSession().getAttribute("member");
			String fileName = (String)request.getSession().getAttribute("fileName");
			Story s=new Story();
			s.setBody(str);
			s.setPhotono(fileName);
			s.setUsername(m.getUsername());
			SaveStoryService service=new SaveStoryServiceIpmt();
			service.save(s);	
		}
		String savepath=getServletContext().getRealPath("/upload");
		String tempPath =getServletContext().getRealPath("/WEB-INF/temp");
		File tmpFile = new File(tempPath);
	    if (!tmpFile.exists()) {
	        // 创建临时目录
	     	tmpFile.mkdir();
	    }
	    DiskFileItemFactory factory = new DiskFileItemFactory();
	    factory.setSizeThreshold(1024 * 100);// 设置缓冲区的大小为100KB，如果不指定，那么缓冲区的大小默认是10KB
	    factory.setRepository(new File(tempPath));// 设置上传时文件的保存目录
	    // 2.创建文件上传解析器
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 设置允许上传文件的内存，这里设置为100KB，根据实际情况设置
        upload.setSizeMax(1024 * 1024 * 15);
	    // 3.判断提交上来的数据是否是上传表单的数据
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                // 4、使用ServletFileUpload解析器解析上传数据，解析结果返回的是一个List<FileItem>集合，每一个FileItem对应一个Form表单的输入项
                List<FileItem> list = upload.parseRequest(request);
               // 设置解析到的文件编码格式
                upload.setHeaderEncoding("utf-8");
                for (FileItem fileItem : list) {
                    // 判断是否文件，结果为“true”就是普通表单，如果为“false”则是文件
                    if (fileItem.isFormField()) {
                        String fileName = fileItem.getFieldName();// 获得表单name属性名
                        
                    } else {
                    	// 获取上传文件的名字
                        String name=System.currentTimeMillis()+".jpg";
                        request.getSession().setAttribute("fileName", name);
                        // 限制上传文件的类型
                        List<String> fileType = Arrays.asList("jpg");//允许上传文件的类型
                        String fileExtName = name.substring(name.lastIndexOf(".") + 1);//获得文件的后缀名
                        //System.out.println("上传文件的后缀名为:"+fileExtName);
                        if (!fileType.contains(fileExtName)) {
                            System.out.println("上传失败！文件类型只能是jpg!");
                        } else {
                            InputStream input = fileItem.getInputStream();// 获得上传文件字节流

                            // 创建输出文件
                            String outPath = request.getServletContext().getRealPath(name);
                            System.out.println("outPath"+outPath);
                            String [] outPath1 = outPath.split("\\\\");
                            StringBuffer sb=new StringBuffer();
                            for(int i=0;i<outPath1.length;i++) {
                            	
                            	if(i==outPath1.length-2) {
                            		sb.append(outPath1[i]);
                            		sb.append("\\story\\Pl_story.baihe.com_1\\story\\album\\happiness\\");
                            	}else if(i==outPath1.length-1) {
                            		sb.append(outPath1[i]);
                            	}
                            	else {
                            		sb.append(outPath1[i]);
                                	sb.append("\\");
                            	}
                            }
                            System.out.println("sb"+sb);
                            FileOutputStream output = new FileOutputStream(new File(sb.toString()));
                            // 使用IOUtils工具输出，也就是copy文件
                            IOUtils.copy(input, output);
                             System.out.println("上传成功！");
                             System.out.println("保存的路径为：" + sb);
                            // 关闭输入流
                            input.close();
                            // 关闭输出流
                            output.close();
                            // 删除处理文件上传时生成的临时文件
                            fileItem.delete();
                        }
                    }
                }
             
            } catch (FileUploadBase.SizeLimitExceededException e) {
                System.out.println("上传失败！上传的文件大小超出限制，最大只能上传"+upload.getSizeMax()+"bytes的文件");
            } catch (Exception e) {
                System.out.println("上传失败！");
                e.printStackTrace();
            }
        } else {
            // 如果不是文件上传类型，则采用普通表单获取方式
            request.setCharacterEncoding("UTF-8");
            String parameter = request.getParameter("para"+"username");
        }
	  response.sendRedirect("/zzLoveProduct/showStoryServlet");
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}